package com.diaohw.module.system.service.impl;

import com.diaohw.module.system.mapper.MenuMapper;
import com.diaohw.module.system.obj.dto.MenuDto;
import com.diaohw.module.system.obj.entity.Menu;
import com.diaohw.module.system.obj.query.MenuQuery;
import com.diaohw.module.system.obj.vo.MenuTreeVo;
import com.diaohw.module.system.obj.vo.MenuVo;
import com.diaohw.module.system.service.MenuService;
import com.diaohw.platform.common.obj.page.PageResultVo;
import com.diaohw.platform.common.util.TreeUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.diaohw.module.system.obj.mapstruct.MenuMapstruct.INSTANCE;

/**
 * <p>
 * 菜单 服务实现类
 * </p>
 *
 * @author D-Hw
 * @since 2024-07-05
 */
@Service
public class MenuImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public MenuVo create(MenuDto data) {
        Menu model = INSTANCE.dtoToEntity(data);
        menuMapper.insert(model);
        return INSTANCE.entityToVo(model);
    }

    @Override
    public MenuVo update(String id, MenuDto data) {
        Menu model = INSTANCE.dtoToEntity(data);
        model.setId(id);
        menuMapper.update(model);
        return INSTANCE.entityToVo(model);
    }

    @Override
    public Boolean delete(String id) {
        return menuMapper.deleteById(id) > 0;
    }

    @Override
    public MenuVo detail(String id) {
        Menu model = menuMapper.selectOneById(id);
        return INSTANCE.entityToVo(model);
    }

    @Override
    public List<MenuVo> findByList(MenuQuery query) {
        QueryWrapper wrapper = MenuMapper.createWrapper(query);
        List<Menu> list = menuMapper.selectListByQuery(wrapper);
        return INSTANCE.entityToVo(list);
    }

    @Override
    public PageResultVo<MenuVo> findByPage(MenuQuery query) {
        QueryWrapper wrapper = MenuMapper.createWrapper(query);

        Page<Menu> page = menuMapper.paginate(query.getPageIndex(), query.getPageSize(), wrapper);
        List<Menu> records = page.getRecords();
        return PageResultVo.create(page.getTotalRow(), INSTANCE.entityToVo(records));
    }

    @Override
    public List<MenuTreeVo> tree() {
        List<Menu> list1 = menuMapper.selectListByQuery(QueryWrapper.create());
        List<MenuTreeVo> list = INSTANCE.entityToTree(list1);
        return TreeUtil.listToTree(list, MenuTreeVo::getId, MenuTreeVo::getParentId, MenuTreeVo::getChildren);
    }


}
